/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jmediaplayer.threads;
import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import jmediaplayer.FormMain;
import jmediaplayer.UsefulFunctions;
import jmediaplayer.setting;
import misc.OpenSubtitlesHasher;

/**
 *
 * @author dean.williams
 */
public class ThreadLoadMedia implements Runnable {

	public static HashMap<Integer,String[]> mediaData = new HashMap<Integer,String[]>();
	public static Boolean abortThread = false;
	private Runtime rt = Runtime.getRuntime();
	private String nodePath = "";
	private List nodeArray;

	public ThreadLoadMedia(String vnodePath,List vnodeArray) {
		nodePath = vnodePath;
		nodeArray = vnodeArray;
	}

	public void DropMediaToPanel(String path, List pathA) {
		File fhandle = new File(path);
		File[] files = fhandle.listFiles();
		String fileHash = "";
		SQLiteConnection db = new SQLiteConnection(new File(setting.get("storeDirectory") + "MediaStore.db"));
		HashMap<String,HashMap<String,String>> catFiles = new HashMap<String,HashMap<String,String>>();
		String[] mediaD = null;

		//empty media lister (will we need to do this all the time?)
		FormMain.jMediaLister.removeAll();
		FormMain.jMediaLister.setModel(new DefaultListModel());


		//What mode are we dabbling?
		System.out.println(pathA.size());
		if (pathA.size() > 1 && pathA.get(1).toString().equals("Video")) {
			if (pathA.size() == 2) {
				System.out.println("Mode: All Video");
			} else if (pathA.size() == 3) {
				System.out.println("Mode: Video Category");
			}
		}

		//Fetch all data for category
		try {
			db.open();
			SQLiteStatement st = db.prepare("SELECT * FROM files WHERE base = '" + pathA.get(1).toString() + "'");
			int step = 0;
			while (st.step()) {
				for(int i=0; i<=st.columnCount(); i++) {
					HashMap<String,String> inner = new HashMap<String,String>();
					inner.put(st.getColumnName(i),st.columnString(i));
					//store it as a key with file path and filename
					catFiles.put(st.columnString(3) + st.columnString(4) , inner);
				}
				step++;
			}
			st.dispose();
			db.dispose();
		} catch (SQLiteException ex) {
			Logger.getLogger(UsefulFunctions.class.getName()).log(Level.SEVERE, null, ex);
		}

		boolean mInDB;
		int count = 0;

		//Clean the garbage?
		mediaData.clear();
		rt.gc();

		//Read all the files in the category
		for (int i = 0; i < files.length; i++) {

			//Check for aborts
			if (abortThread == true) {
				abortThread = false;
				return;
			}

			//We do not want to ever read hidden files in this process.
			if (!files[i].getName().startsWith(".") || !files[i].isHidden()) {
				if (files[i].isDirectory()) {
					//We will ignore these. for now??!?
					//sub Directory will be looked on as a group!
				} else {

					//Generate the hash
					try {
						fileHash = OpenSubtitlesHasher.computeHash(files[i]);
					} catch (IOException ex) {
						Logger.getLogger(UsefulFunctions.class.getName()).log(Level.SEVERE, null, ex);
					}

					//Check if it exists in the DB yet
					if (catFiles.containsKey(path + files[i].getName())) {
						//Set flag so we ignore dialog options (its in the DB so make sure it's displayed.
						mInDB = true;

						//Read the data from the DB into the
					} else {

						//Figure out known information and display dialog
						mInDB = false;
						String mFileName = files[i].getName().substring(0, files[i].getName().indexOf("."));
						String mFileExt = files[i].getName().substring(files[i].getName().indexOf("."));
						FormMain.NMLPath.setText("<html><b>Path:</b> <font style='color:red'>" + path + mFileName + mFileExt + "</font></html>");
						FormMain.NMName.setText(mFileName);
						FormMain.NMOrigName = mFileName;
						FormMain.NMOrigPath = path;
						FormMain.NMOrigExt = mFileExt;
						FormMain.NMHash = fileHash;

						//dont show dialog if set to ignore :)
						if (FormMain.mSkipAll == false && FormMain.mAddAll == false) {
							FormMain.NMDialog.setVisible(true);

							//INFO: Even though in theory the form should wait while the dialogs are shown, sometimes cycles seem to get through so this is to make sure nothing is sent until the user has completed the dialogs
							do {
								//Slow down the cycles (WE dont want thousands of checks a second!)
								waiting(200);
							} while (FormMain.NMDialog.isVisible() || FormMain.MSDialog.isVisible());
						}

						//Insert the data into the DB

						//Setup the data array
						// 0 = Media Name
						//1 = path
						//2 = filename
						//3 = ext
						//4 = filehash
						//5 = description
						mediaD = new String[] {FormMain.NMName.getText(), FormMain.NMOrigPath, FormMain.NMName.getText(), FormMain.NMOrigExt, fileHash, FormMain.NMDesc.getText()};
					}

					//Add to panel
					if (FormMain.mSkipAll == false && FormMain.mSkip == false || mInDB == true) {
						//INFO: We access "mediaData" from the panel!
						((DefaultListModel)FormMain.jMediaLister.getModel()).addElement(count);
						mediaData.put(count,mediaD);
						count ++;

						//INFO: Slowing down the process a little bit, but may remove this?
						waiting(20);
					}

					//remove skip.
					FormMain.mSkip = false;
				}
			}
		}

		//Clean the garbage?
		catFiles.clear();
		rt.gc();

		//Reset the ignore  and add all
		FormMain.mSkipAll = false;
		//FormMain.mSkip = false; Not required?
		FormMain.mAddAll = false;
	}

	//Copy from UsefulFunctions
	private static void waiting (int n){
         long t0, t1;

         t0 =  System.currentTimeMillis();
         do {
			t1 = System.currentTimeMillis();
         }
         while (t1 - t0 < n);

		 t0 = 0;
		 t1 = 0;
     }

	@Override
	public void run() {
		abortThread = false;
		DropMediaToPanel(nodePath, nodeArray);
	}
}
